<template>
  <div>
    <Form :label-width="100" ref="dataToQuery" :model="dataToQuery">
      <Row :gutter="16" class="query-form">
        <i-col span="8">
          <FormItem label="项目大类：" prop="auditName">
            <Input v-model="dataToQuery.categoryName"/>
          </FormItem>
        </i-col>
        <i-col span="8">

        </i-col>
        <i-col span="8">
          <div style="float: right">
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
            <Button class="ivu-btn-query" icon="md-search"  @click="dataToquery">查询</Button>
          </div>
        </i-col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" type="success" class="ivu-btn-add" icon="md-add"
                  v-if="this.user.loginId === this.Common.admin || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7' || obj.roleId == '6a57d3bde6544c4495ceace17399fd26') != undefined"
                  @click="addInfo">新增
          </Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :loading="loading" border :columns="columns" no-data-text="请选择审计标准"
           :data="dataTable" width="100%" :height="tableHeight"  highlight-row stripe size="small"></Table>
    <Row type="flex" justify="end" >
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
      </i-col>
    </Row>
    <Modal :title="add?'审计项目大类新增':'审计项目大类修改'" :transfer=false v-model="model1" :width=900>
      <Row>
        <Col span="24">
          <Form ref="dataToView" :model="dataToView" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="所属二级集团：" prop="twoOrgName">
                  <Input v-model="dataToView.twoOrgName" :readonly="true"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="审计标准名称：" prop="auditName">
                  <Input v-model="dataToView.auditName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="板块：" >
                  <Input v-model="dataToView.auditPlate" :readonly="true"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="序号：" prop="num">
                  <InputNumber  :min="1" v-model="dataToView.num" style="width: 100%;"></InputNumber>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="项目大类：" prop="categoryName">
                  <Input v-model="dataToView.categoryName"/>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：" prop="userName">
                  <Input v-model="dataToView.userName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报时间:" prop="createDate">
                  <Input v-model="dataToView.createDate" :readonly="true"/>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button  class='ivu-btn-save' :loading="buttonLoading"
                @click="submit('dataToView')">确定
        </Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="审计项目大类详情" :transfer=false v-model="model2" :width=800 class="modal-view-detail">
      <Row>
        <Col span="24">
          <Form :model="dataToView" :label-width="160">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="所属二级集团：" >
                  {{dataToView.twoOrgName}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="11">
                <FormItem label="审计标准名称:" >
                  {{dataToView.auditName}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="板块:" >
                  {{dataToView.auditPlate}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="序号：" prop="num">
                  {{dataToView.num}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="项目大类：" prop="categoryName">
                  {{dataToView.categoryName}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：" >
                  {{dataToView.userName}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报时间：" >
                  {{formatDate(new Date(dataToView.createDate),'yyyy-MM-dd')}}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {sessionStorage} from "@/common/cacheUtils";
import {Api} from "@/api";

export default {
name: "StandardsTable",
  props:['type'],
  data(){
    return{
      add:false,
      loading:false,
      buttonLoading:false,
      tableHeight:null,
      model1:false,
      model2:false,
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      twoLevelOrgId:null,
      twoLevelOrgName:null,
      dataTable:[],
      dataToView:{},
      pageSizeArray: [10, 20, 50],
      dataToQuery:{},
      columns:[
        {
          title: "序号",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '项目大类',
          minWidth: 200,
          align: 'center',
          key: 'categoryName',
        },
        {
          title: '所属二级集团',
          minWidth: 200,
          align: 'center',
          key: 'twoOrgName',
        },
        {
          title: '审计名称',
          minWidth: 150,
          align: 'center',
          key: 'auditName',
        },
        {
          title: '板块',
          minWidth: 150,
          align: 'center',
          key: 'auditPlate',
        },



        {
          title: '填报人',
          minWidth: 150,
          align: 'center',
          key: 'userName',
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 160,
          fixed: 'right',
          render: (h, params) => {
            if (this.user.loginId === this.Common.admin
                || this.user.userId === params.row.createUserId
                || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined
                || this.user.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',

                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: '<p>是否要删除？</p>',
                        onOk: () => {
                          this.deleteData(params);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, '删除')
              ]);
            }else{
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }

          }
        },

      ],
      ruleCustom:{
        twoLevelGroupName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        categoryName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        num: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        userName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        createDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      user:sessionStorage('userId').getObject('userId'),
      saveUrl:Api.saveAuditCategory,
      updateUrl:Api.updateAuditCategory,
      queryUrl:Api.queryAuditCategory,
      deleteUrl:Api.deleteAuditCategory,
      data:{},

    }
  },
  mounted(){
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
  },
  methods:{
    showData(data, flag) {
      this.dataToView =  JSON.parse(JSON.stringify(data.row));
      if (flag == 1) {
        //查看页面
        this.model2 = true;
      } else {
        this.$set(this.dataToView,'createDate',this.formatDate(new Date(this.dataToView.createDate),'yyyy-MM-dd'))
        this.buttonLoading = false;
        this.add = false;
        this.model1 = true;
      }
    },
    setTwoLevelOrgId(item){
      this.data = item
      this.query();
    },
    pageSizeChange(pageSize){
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    pageChange(pageNum){
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    cancel() {
      this.dataToQuery = {};
      this.query();
    },
    query(){
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,

      };
      this.$set(this.dataToQuery,'standardsId',this.data.id)
      this.$set(this.dataToQuery,'categoryType',this.type)
      data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
      this.$http.get(this.queryUrl, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败");
        this.loading = false;
      })
    },
    dataToquery(){
      this.pagedata.currentPage = 1;
      this.query();
    },
    addInfo(){
      this.dataToView = {
        userName:this.user.userName,
        createDate:this.formatDate(new Date(),'yyyy-MM-dd'),
        twoOrgName:this.data.twoLevelGroupName,
        auditName:this.data.auditName,
        auditPlate:this.data.auditPlate,
        standardsId:this.data.id,
        categoryType:this.type,
        num:1,
      };
      this.add = true;
      this.model1 = true;

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          let userId = this.user.userId;
          let orgId = this.user.orgInfo.orgId;
          if (this.add) {
            this.dataToView.createUsrId = userId;
            this.dataToView.createOrgId = orgId;
            this.$http.post(this.saveUrl, this.dataToView).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.saveMod = false;
                this.$emit('update','2');
                this.query()
              }else{
                this.$Message.error(res.data.msg);
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("新增失败")
            })
          } else {
            this.dataToView.updateUserId = userId;
            this.dataToView.updateOrgId = orgId;
            this.$http.put(this.updateUrl, this.dataToView).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.$emit('update','2');
                this.query()

              } else{
                this.$Message.error(res.data.msg);
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("修改失败")
            })
          }



        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    handleCancel(){
      this.model1 = false;
      this.dataToView = {};
    },
    deleteData(params) {
      this.$http.delete(this.deleteUrl + '/' + params.row.id, {params: {}}).then((res) => {
        if (res.data.status === 200) {
          this.$emit('update','2');
          this.$Message.success('成功');
          this.query()
        } else{
          this.$Message.error(res.data.msg);
        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
  }

}
</script>

<style scoped>

</style>
